//加载express模块
const express = require("express")
//加载cors模块
const cors = require("cors")
//加载mysql模块
const mysql = require("mysql")

const jwt = require('./jwt')

const bodyparser = require("body-parser")



//创建线程池
const pool = mysql.createPool({
  host: 'localhost',
  port: '3306',
  user: 'root',
  password: 'w075792.',
  database: 'icecream',
  connectionLimit: 15
});

const server = express()

server.use(cors({
  origin: ['http://localhost:8080', "http://192.168.0.100:8080"]
}))

server.use(bodyparser.json())



//获取所有商品
server.get('/shop', (req, res) => {
  // console.log(req);
  let sql = 'SELECT * FROM shop';
  pool.query(sql, [], (err, result) => {
    if (err) throw err
    res.send({ message: '查询成功', code: 200, result: result })
  })
})

//获取商品详情
server.get('/shopdetail', (req, res) => {
  let s_id = req.query.sid;
  let sql = 'SELECT * FROM shopdetail WHERE s_id=?';
  pool.query(sql, [s_id], (err, result) => {
    if (err) throw err;
    res.send({ message: '查询商品详情成功', code: 200, result: result });
  })
})

//用户登录
server.post('/login', (req, res) => {
  // console.log(req);
  // console.log(res);
  let { uname, upwd } = req.body
  let sql = 'select uid,uname,avatar,phone,birthday,gender from ice_user where uname=?&&upwd=?';
  pool.query(sql, [uname, upwd], (err, result) => {
    // console.log(err);
    console.log(result);
    if (err) throw err
    if (result.length == 0) {
      res.send({
        message: '账号或密码错误',
        code: 8001
      })
    }
    else {
      res.send({
        message: '登录成功',
        code: 200,
        result: result[0],
        token: jwt.generateToken(result[0])
      })
    }
  })
})


//用户注册
server.post('/register', (req, res) => {
  const obj = req.body
  if (!obj.username) {
    res.send({ code: 9001, message: '请输入账号' })
    return
  }
  if (!obj.password) {
    res.send({ code: 9002, message: '请输入密码' })
    return
  }
  if (!obj.phone) {
    res.send({ code: 9003, message: '请输入账号' })
    return
  }
  if (!obj.birthday) {
    res.send({ code: 9004, message: '请输入账号' })
    return
  }
  if (!obj.gender) {
    res.send({ code: 9005, message: '请输入性别' })
    return
  }
  if (!obj.avator) {
    res.send({ code: 9005, message: '请选择头像' })
    return
  }
  const data = {}
  data.uname = obj.username
  data.upwd = obj.password
  data.avatar = obj.avator
  data.phone = obj.phone
  data.birthday = obj.birthday
  data.gender = obj.gender
  pool.query('INSERT INTO ice_user SET ?', [data], (err, result) => {
    if (err) throw err
    console.log(result);
    res.send({ code: 200, message: '注册成功' })
  })
})

server.post('/addShopCart', (req, res) => {
  // console.log(req.body);
  let totalprice = 0
  req.body.forEach(item => {
    totalprice += item.price * item.count
  })
  let data = {}
  data.uid = req.body[0].uid
  data.shopcart = JSON.stringify(req.body)
  data.totalprice = totalprice
  let sql = 'INSERT INTO order_menu SET ?';
  pool.query(sql, [data], (err, result) => {
    if (err) throw err
    res.send({
      code: 200,
      message: '加入成功'
    })
  })
})

// 获取订单
server.get('/getshopcart', (req, res) => {
  // console.log(req.query);
  let uid = req.query.uid
  let sql = 'SELECT * FROM order_menu WHERE uid=?'
  pool.query(sql, [uid], (err, result) => {
    if (err) throw err;
    res.send({ message: '查询成功', code: 1, result: result });
  })
})

server.get('/getaddress', (req, res) => {
  // console.log(req.query);
  let user_id = req.query.user_id
  let sql = 'SELECT * FROM ice_address WHERE user_id=?'
  pool.query(sql, [user_id], (err, result) => {
    // console.log(result)
    if (err) throw err;
    res.send({ message: '查询成功', code: 1, result: result });
  });
})

//新增地址
server.post('/addaddress', (req, res) => {
  // console.log(req.body);
  let obj = req.body
  let sql = 'INSERT INTO ice_address SET ?';
  pool.query(sql, [obj], (err, result) => {
    if (err) throw err
    if (result.affectedRows > 0) {
      res.send({ message: '添加成功', code: 1 })
    } else {
      res.send({ message: '添加失败', code: 0 })
    }
  })
})

server.listen(3000, () => {
  console.log('服务已监听3000端口');
})